package com.dldata.devtools30.controller.zhibiao;

import com.dldata.devtools30.controller.DevBase30Controller;
import com.dldata.devtools30.entity.DevtModelMetadataFieldEntity;
import com.dldata.devtools30.entity.DevtModelMetadataTableEntity;
import com.dldata.devtools30.entity.DevtZbcfgInfoEntity;
import com.dldata.devtools30.entity.DevtZbobjFieldEntity;
import com.dldata.devtools30.repository.metadata.DevtModelMetadataFieldDao;
import com.dldata.devtools30.repository.metadata.DevtModelMetadataTableDao;
import com.dldata.devtools30.repository.zhibiao.DevtZbcfgInfoEntityDao;
import com.dldata.devtools30.repository.zhibiao.DevtZbobjFieldEntityDao;
import com.dldata.devtools30.utils.Public;
import com.dldata.devtools30.utils.Result;
import com.dldata.devtools30.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/DevtZbcfgInfoEntityController")
public class DevtZbcfgInfoEntityController extends DevBase30Controller {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    DevtZbcfgInfoEntityDao devtZbcfgInfoEntityDao;
    @Autowired
    DevtModelMetadataTableDao devtModelMetadataTableDao;
    @Autowired
    DevtModelMetadataFieldDao devtModelMetadataFieldDao;
    @Autowired
    DevtZbobjFieldEntityDao zbobjFieldEntityDao;

    @RequestMapping(value = "/getAll")
    @ResponseBody
    public Result getAll(@RequestParam Map<String, String> paramMap){
        String zbcalssId = paramMap.get("zbcalssId");
        String serach=paramMap.get("serach");
        serach=StringUtil.isEmptyOrLength0(serach)?"":serach;
        serach="%"+serach+"%";
        List<DevtZbcfgInfoEntity> metadataTypeEntities = devtZbcfgInfoEntityDao.getAllByClassId(zbcalssId,serach);
       
        return Result.ok(metadataTypeEntities);
    }
    
    @RequestMapping(value = "/save")
    @ResponseBody
    public Result save(DevtZbcfgInfoEntity entity){
        if(StringUtil.isEmptyOrLength0(entity.getZbname())){
            return Result.error("指标名称不能为空");
        }
        if(StringUtil.isEmptyOrLength0(entity.getZbsql())){
            return Result.error("指标SQL不能为空");
        }
        if(entity.getXh()==null){
            Integer maxXh = devtZbcfgInfoEntityDao.getMaxXh();
            maxXh=maxXh==null?0:maxXh;
            entity.setXh(maxXh+1);
    
            String suffix=((entity.getXh()/200)+1)+"";
            while (suffix.length()<3){
                suffix="0"+suffix;
            }
            entity.setTablename("devt_zhibiao_val_"+suffix);
        }
        if(StringUtil.isEmptyOrLength0(entity.getTablename())){
            String suffix=((entity.getXh()/200)+1)+"";
            while (suffix.length()<3){
                suffix="0"+suffix;
            }
            entity.setTablename("devt_zhibiao_val_"+suffix);
        }
        //指标编码由序号转成16进制编码，然后不足4位在前面补0，再加上DL打头
        if(StringUtil.isEmptyOrLength0(entity.getZbcode())){
            String zbcode = Integer.toString(entity.getXh(),36).toUpperCase();
            while(zbcode.length()<4){
                zbcode="0"+zbcode;
            }
            zbcode="DL"+zbcode;
            entity.setZbcode(zbcode);
        }
        
        if(StringUtil.isEmptyOrLength0(entity.getId())){
            entity.setId(UUID.randomUUID().toString());
            entity.setCreatetime(new Timestamp(System.currentTimeMillis()));
        }else{
            DevtZbcfgInfoEntity zbcfgInfoEntity = devtZbcfgInfoEntityDao.findById(entity.getId()).orElse(null);
            if(zbcfgInfoEntity!=null){
                entity.setCreatetime(zbcfgInfoEntity.getCreatetime());
            }
        }
    
        //
        List<DevtModelMetadataTableEntity> tableEntities = devtModelMetadataTableDao.getAll();
        Map<String, List<DevtModelMetadataTableEntity>> tableEntitieMap = tableEntities.stream().collect(Collectors.groupingBy(DevtModelMetadataTableEntity::getName));
        Pattern pattern = Pattern.compile(Public.REG_FIELD_ZH);
        Matcher matcher=pattern.matcher(entity.getZbsql());
        while(matcher.find()) {
            for (int i = 0; i <= matcher.groupCount(); i++) {
                String groupValues = matcher.group(i);
                System.out.println(groupValues);
                groupValues=groupValues.replace("[","").replace("]","");
                String[] strings = groupValues.split("\\.");
                String modeltablename=strings[0];
                entity.setModelid(tableEntitieMap.get(modeltablename).get(0).getId());
                String modeltablefieldname=strings[1];
                List<DevtModelMetadataFieldEntity> metadataFieldEntities = devtModelMetadataFieldDao.getAllByTid(entity.getModelid());
                Map<String, List<DevtModelMetadataFieldEntity>> metadataFieldMap = metadataFieldEntities.stream()
                        .collect(Collectors.groupingBy(DevtModelMetadataFieldEntity::getFieldName));
                entity.setFieldcode(metadataFieldMap.get(modeltablefieldname).get(0).getFieldCode());
            }
        }
    
        entity.setUpdatetime(new Timestamp(System.currentTimeMillis()));
        entity.setDelflag(0);
        devtZbcfgInfoEntityDao.save(entity);

        return Result.ok();
    }
    
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Result delete(@RequestParam Map<String, String> paramMap){

        String id =paramMap.get("id");
        if(StringUtil.isEmptyOrLength0(id)){
            return  Result.error("参数有误");
        }
        try {
            DevtZbcfgInfoEntity devtZbclassInfoEntity = devtZbcfgInfoEntityDao.findById(id).orElse(null);
            if(devtZbclassInfoEntity!=null){
                devtZbclassInfoEntity.setDelflag(1);
                devtZbcfgInfoEntityDao.save(devtZbclassInfoEntity);
            }
        }
        catch (Exception ex){
            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage(),ex);
            return  Result.error("操作错误，请稍候再试!");
        }
        return  Result.ok("删除成功");
    }
    
    @RequestMapping("edit")
    @ResponseBody
    public Result toEdit(String zbclassid, Model model){
        DevtZbcfgInfoEntity devtZbcfgInfoEntity = new DevtZbcfgInfoEntity();
        if(!StringUtil.isEmptyOrLength0(zbclassid)){
            devtZbcfgInfoEntity = devtZbcfgInfoEntityDao.findById(zbclassid).orElse(new DevtZbcfgInfoEntity());
        }
        return  Result.ok(devtZbcfgInfoEntity);
    }
    
    @RequestMapping("selModelField")
    public String selModelField(Model model){
        return "thymeleaf/devtools30/zhibiao/v_zhibiaocfgselModelField";
    }
    
    @RequestMapping("sqlPriview")
    public String sqlPriview(@RequestParam Map<String, String> paramMap, Model model){
        DevtModelMetadataTableEntity metadataTableEntity =null;
        DevtModelMetadataFieldEntity metadataFieldEntity =null;
        List<DevtModelMetadataTableEntity> tableEntities = devtModelMetadataTableDao.getAll();
        Map<String, List<DevtModelMetadataTableEntity>> tableEntitieMap = tableEntities.stream().collect(Collectors.groupingBy(DevtModelMetadataTableEntity::getName));
        Pattern pattern = Pattern.compile(Public.REG_FIELD_ZH);
        String zbsql = paramMap.get("zbsql");
        zbsql=URLDecoder.decode(paramMap.get("zbsql"));
        Matcher matcher=pattern.matcher(zbsql);
        while(matcher.find()) {
            for (int i = 0; i <= matcher.groupCount(); i++) {
                String groupValues = matcher.group(i);
                System.out.println(groupValues);
                groupValues=groupValues.replace("[","").replace("]","");
                String[] strings = groupValues.split("\\.");
                String modeltablename=strings[0];
                metadataTableEntity = tableEntitieMap.get(modeltablename).get(0);
                
                String modeltablefieldname=strings[1];
                List<DevtModelMetadataFieldEntity> metadataFieldEntities = devtModelMetadataFieldDao.getAllByTid(metadataTableEntity.getId());
                Map<String, List<DevtModelMetadataFieldEntity>> metadataFieldMap = metadataFieldEntities.stream()
                        .collect(Collectors.groupingBy(DevtModelMetadataFieldEntity::getFieldName));
                metadataFieldEntity = metadataFieldMap.get(modeltablefieldname).get(0);
            }
        }
    
        List<DevtZbobjFieldEntity> metadataTypeEntities = zbobjFieldEntityDao.getAllByModelId(metadataTableEntity.getId());
        HashSet<String> fieldCodeSet=new HashSet<>();
        for (int i = 0; i < metadataTypeEntities.size(); i++) {
            DevtZbobjFieldEntity devtZbobjFieldEntity = metadataTypeEntities.get(i);
            fieldCodeSet.add(devtZbobjFieldEntity.getModelfieldcode());
        }
        StringBuilder stringBuilder=new StringBuilder();
        for (Iterator<String> iterator = fieldCodeSet.iterator(); iterator.hasNext(); ) {
            String fieldCode = iterator.next();
            stringBuilder.append(fieldCode);
            stringBuilder.append(",");
        }
        if(stringBuilder.length()>0){
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
        }
 
        String sqlgroupby=stringBuilder.toString();
        String sqlVal= zbsql.replace(metadataTableEntity.getName(),metadataTableEntity.getCode())
                .replace(metadataFieldEntity.getFieldName(),metadataFieldEntity.getFieldCode());
        String sqltable=metadataTableEntity.getCode();
        String zbrealsql="select "+sqlVal+" as zbval , "+sqlgroupby +" from "+sqltable+" group by "+sqlgroupby;
        model.addAttribute("zbrealsql",zbrealsql);
        return "thymeleaf/devtools30/zhibiao/v_zhibiaocfgSqlPriview";
    }
}
